package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.User;
import org.aeon.entity.dto.UserVerificationDto;
import org.aeon.message.request.LoginRequestMessage;
import org.aeon.message.request.RegisterRequestMessage;
import org.aeon.message.response.RegisterResponseMessage;
import org.aeon.service.factory.UserServiceFactory;

/**
 * @author: MissingAeon
 * @date: 2024/1/27 11:52
 * @description:
 */
@Slf4j
@ChannelHandler.Sharable
public class RegisterRequestHandler extends SimpleChannelInboundHandler<RegisterRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RegisterRequestMessage msg) throws Exception {
        final RegisterResponseMessage resMsg = new RegisterResponseMessage();
        resMsg.setResponseID(msg.getUid());

        // 检查相同用户名
        final Long userId = UserServiceFactory.getService().getUserId(msg.getUser().getUsername());
        if (userId != null) {
            resMsg.setResponse(false, "用户名重复！");
        } else {
            // 尝试注册
            final User user = UserServiceFactory.getService().register(msg.getUser());
            if (user == null) {
                resMsg.setResponse(false, "注册失败！");
            } else {
                // 成功返回
                resMsg.setResponse(true, "注册成功");
                resMsg.setUser(msg.getUser());

                // 同时登陆
                ctx.fireChannelRead(new LoginRequestMessage(new UserVerificationDto(msg.getUser().getUsername(), msg.getUser().getPassword())));
            }
        }
        ctx.writeAndFlush(resMsg);
    }
}
